import java.util.Arrays;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-09-20
 * Time: 8:19
 */
public class HashBuck2<K,V> {//泛型
    class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }
    //泛型数组
    public Node<K,V>[] arr =(Node<K, V>[]) new Node[10];
    public int usedsize;

    //构造方法
//    public HashBuck2(Node<K, V>[] arr, int usedsize) {
//        this.arr = arr;
//        this.usedsize = usedsize;
//    }

    @Override
    public boolean equals(Object o) {

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashBuck2<?, ?> hashBuck2 = (HashBuck2<?, ?>) o;
        return usedsize == hashBuck2.usedsize && Arrays.equals(arr, hashBuck2.arr);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(usedsize);
        result = 31 * result + Arrays.hashCode(arr);
        return result;
    }

    /**
     * add
     */
    public void add(K key,V val){
        Node<K,V> node = new Node<>(key,val);
        int hash = key.hashCode();
        int index = hash%arr.length;
        Node<K,V> cur = arr[index];
        while(cur != null){
            if(cur.key.equals(node.key)){//key一样,直接覆盖value
                cur.val = node.val;
            }
                cur = cur.next;
        }
        //没有找到key一样,头插
        node.next = arr[index];
        arr[index] = node;
        //扩容
    }
    /**
     * get
     */
    public V get(K key){
        int hash = key.hashCode();
        int index = hash%arr.length;
        Node<K,V> cur = arr[index];
        while(cur != null){
            if(cur.key.equals(key)){//key一样,直接覆盖value
               return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
